﻿using Baidu.Aip.Ocr;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyORC
{

    public delegate void transPathHandler(string str);

    public partial class Frm_InfoReg : Form
    {
        private string dbPath;

        private string globalapi_key;

        private string globalapp_id;

        private string globalsecret_key;

        private string logTxtFulPath;

        private bool first;

        private bool logTxtBool;

        private Zdxx zdxx;

        private Thread thread;

        private bool killThread = false;

        public bool BaiDuValid = true;

        public Frm_InfoReg()
        {
            InitializeComponent();
        }

        public Frm_InfoReg(string globalapp_id, string globalapi_key, string globalsecret_key)
        {
            InitializeComponent();
            this.globalapp_id = globalapp_id;
            this.globalapi_key = globalapi_key;
            this.globalsecret_key = globalsecret_key;
        }

        public event transPathHandler TransPath;

        private void openImgDirButton_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbGDB = new FolderBrowserDialog();
            fbGDB.Description = "请选择文件夹";
            if (fbGDB.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = fbGDB.SelectedPath;
            }
        }

        private void openDbfileButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = "c://";
            openFileDialog.Filter = "数据库文件|*.mdb";
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {

                dbPath = openFileDialog.FileName;
                textBox2.Text = dbPath;
                TransPath(dbPath);
            }
        }

        private void OKButton_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Trim() == "")
            {
                MessageBox.Show("文件夹路径不能为空，请重新选择！");
                return;
            }
            if (textBox2.Text.Trim() == "")
            {
                MessageBox.Show("请选择数据库文件！");
                return;
            }
            if (AccessHelper.GetTableName(dbPath).Contains("zdxx"))
            {
                first = true;
                logTxtFulPath = Directory.GetCurrentDirectory() + "\\log\\" + DateTime.Now.ToLocalTime().ToString("yyyyMMdd_HHmmss") + ".txt";
                logTxtBool = true;
                progressBar1.Visible = true;
                openDbfileButton.Enabled = false;
                openImgDirButton.Enabled = false;
                OKButton.Enabled = false;
                //StartReg();
                killThread = false;
                thread = new Thread(StartReg);
                thread.IsBackground = true;
                thread.Start();
            }
            else
            {
                MessageBox.Show("没有在该数据库中找到表名为“zdxx”的表！");
            }
            
        }

        private void StartReg()
        {

            DataTable dt = AccessHelper.getDataTabaleNoClose(dbPath, "select * from zdxx");

            List<string> colname = new List<string>();

            foreach (DataColumn dc in dt.Columns)
            {
                colname.Add(dc.ColumnName);
            }
            if (first)
            {
                first = false;
                if (!colname.Contains("新权利人"))
                {
                    AccessHelper.excuteSqlNoClose(dbPath, "alter table zdxx add COLUMN 新权利人 Text(255)");
                }
                if (!colname.Contains("建房年代"))
                {
                    AccessHelper.excuteSqlNoClose(dbPath, "alter table zdxx add COLUMN 建房年代 Text(255)");
                }
                if (!colname.Contains("备注2"))
                {
                    AccessHelper.excuteSqlNoClose(dbPath, "alter table zdxx add COLUMN 备注2 Text(255)");
                }
                if (!colname.Contains("身份证号"))
                {
                    AccessHelper.excuteSqlNoClose(dbPath, "alter table zdxx add COLUMN 身份证号 Text(255)");
                }
                if (!colname.Contains("证件类型名称"))
                {
                    AccessHelper.excuteSqlNoClose(dbPath, "alter table zdxx add COLUMN 证件类型名称 Text(255)");
                }
                if (!colname.Contains("性别"))
                {
                    AccessHelper.excuteSqlNoClose(dbPath, "alter table zdxx add COLUMN 性别 Text(255)");
                }
                if (!colname.Contains("电话号码"))
                {
                    AccessHelper.excuteSqlNoClose(dbPath, "alter table zdxx add COLUMN 电话号码 Text(255)");
                }
                if (!colname.Contains("通讯地址"))
                {
                    AccessHelper.excuteSqlNoClose(dbPath, "alter table zdxx add COLUMN 通讯地址 Text(255)");
                }
                if (!colname.Contains("邮政编码"))
                {
                    AccessHelper.excuteSqlNoClose(dbPath, "alter table zdxx add COLUMN 邮政编码 Text(255)");
                }
                if (!colname.Contains("与户主关系"))
                {
                    AccessHelper.excuteSqlNoClose(dbPath, "alter table zdxx add COLUMN 与户主关系 Text(255)");
                }
                if (!colname.Contains("备注"))
                {
                    AccessHelper.excuteSqlNoClose(dbPath, "alter table zdxx add COLUMN 备注 Text(255)");
                }
                if (!colname.Contains("权利人类型名称"))
                {
                    AccessHelper.excuteSqlNoClose(dbPath, "alter table zdxx add COLUMN 权利人类型名称 Text(255)");
                }
                if (!colname.Contains("权利类型名称"))
                {
                    AccessHelper.excuteSqlNoClose(dbPath, "alter table zdxx add COLUMN 权利类型名称 Text(255)");
                }
                if (!colname.Contains("共有方式名称"))
                {
                    AccessHelper.excuteSqlNoClose(dbPath, "alter table zdxx add COLUMN 共有方式名称 Text(255)");
                }
                if (!colname.Contains("共有情况"))
                {
                    AccessHelper.excuteSqlNoClose(dbPath, "alter table zdxx add COLUMN 共有情况 Text(255)");
                }
            }

            GetAllDirList(textBox1.Text.Trim());
            progressBar1.Visible = false;
            openDbfileButton.Enabled = true;
            openImgDirButton.Enabled = true;
            OKButton.Enabled = true;
            if (killThread)
            {
                
                if (!logTxtBool)
                {
                    MessageBox.Show("身份识别过程已终止，识别结果以保存\r\n错误部分请根据时间查看日志记录！");
                    Process.Start("explorer.exe", AppDomain.CurrentDomain.BaseDirectory + "log\\");
                }
                else
                {
                    MessageBox.Show("身份识别过程已终止，识别结果以保存\r\n");
                }
            }
            else
            {
                if (!logTxtBool)
                {
                    MessageBox.Show("身份证识别完成，错误部分请根据时间查看日志记录！");
                    Process.Start("explorer.exe", AppDomain.CurrentDomain.BaseDirectory + "log\\");
                }
                else
                {
                    MessageBox.Show("身份证识别完成！");
                }
            }
            
            AccessHelper.closeConnection();
        }

        private bool GetAllDirList(string strBaseDir)
        {
            
            if (killThread)
            {
                return killThread;
            }
            DirectoryInfo di = new DirectoryInfo(strBaseDir);
            DirectoryInfo[] diA = di.GetDirectories();
            for (int i = 0; i < diA.Length; i++)
            {
                StartWork(diA[i].FullName);
                if (GetAllDirList(diA[i].FullName))
                {
                    break;
                }
            }
         //   MessageBox.Show(killThread.ToString());
            return killThread;
        }

        private void StartWork(string filePath)
        {
            string[] files = Directory.GetFiles(filePath);
            string[] array = files;
            if (array.Length > 0)
            {
                zdxx = new Zdxx();
                string[] strs = filePath.Split('\\');
                zdxx.zdh = strs[strs.Length - 1];
                DataTable dt = AccessHelper.getDataTabaleNoClose(dbPath, "select * from zdxx where 宗地号 = '" + zdxx.zdh + "'");
                if (dt.Rows.Count == 0 || (dt.Rows.Count > 0 && dt.Rows[0]["身份证号"].ToString().Trim().Equals("") && !dt.Rows[0]["备注2"].ToString().Trim().Contains("未能正确识别证件"))) 
                {
                    foreach (string filenametemp in array)
                    {
                        if (filenametemp.Substring(filenametemp.Length - 4, 4).ToLower() == ".png" || filenametemp.Substring(filenametemp.Length - 4, 4).ToLower() == ".jpg" || filenametemp.Substring(filenametemp.Length - 4, 4).ToLower() == ".txt")
                        {
                            string jpgName = Path.GetFileNameWithoutExtension(filenametemp);
                            if (jpgName.Contains("+"))
                            {
                                int plusCount = jpgName.Length - jpgName.Replace("+", "").Length;
                                string[] phone_year = jpgName.Split('+');
                                if (plusCount == 2)
                                {
                                    zdxx.dhhm = phone_year[0];
                                    zdxx.jfnd = phone_year[1];
                                }
                                if (plusCount == 5)
                                {
                                    for (int i = 0; i < phone_year.Length; i++)
                                    {
                                        if (phone_year[i].Equals("@"))
                                        {
                                            phone_year[i] = "";
                                        }
                                    }
                                    zdxx.dhhm = phone_year[0];
                                    zdxx.jfnd = phone_year[1];
                                    zdxx.yhzgx = phone_year[2];
                                    zdxx.yyqlrgx = phone_year[3];
                                    zdxx.bz2 = phone_year[4];
                                    if (File.Exists(filePath + "\\error"))
                                    {
                                        zdxx.bz2 = "该资料存在一些问题," + zdxx.bz2;
                                    }
                                    if (phone_year[5][0].Equals('1'))
                                    {
                                        zdxx.bz2 = "新增宗地," + zdxx.bz2;
                                    }
                                }
                            }

                            if (jpgName.Contains("身份证01"))
                            {
                                IdcardReg(filenametemp);
                            }
                        }
                    }
                    if (!killThread)
                    {
                        updataDb(zdxx);
                    }
                }
            }
        }

        private void updataDb(Zdxx zdxx)
        {


            string sql = "";
            //  string binpath = Directory.GetCurrentDirectory();
            sql = "SELECT * FROM zdxx WHERE 宗地号 = '" + zdxx.zdh + "'";
            DataTable dt = AccessHelper.getDataTabaleNoClose(dbPath, sql);
            if (dt.Rows.Count == 0)
            {
                if (!zdxx.bz2.Contains("新增宗地"))
                {
                    zdxx.bz2 = "疑似新增宗地," + zdxx.bz2;
                }

                sql = "INSERT INTO zdxx(宗地号,权利人,新权利人,身份证号,证件类型名称,性别,电话号码,通讯地址,邮政编码,建房年代,与户主关系,备注,权利人类型名称,权利类型名称,共有方式名称,共有情况,备注2) VALUES('" + zdxx.zdh + "','" + zdxx.yqlr + "','" + zdxx.qlr + "','" + zdxx.sfzh + "','" + zdxx.zjlxmc + "','" + zdxx.xb + "','" + zdxx.dhhm + "','" + zdxx.txdz + "','" + zdxx.yzbm + "','" + zdxx.jfnd + "','" + zdxx.yhzgx + "','" + zdxx.bz1 + "','" + zdxx.qlrlxmc + "','" + zdxx.qllxmc + "','" + zdxx.gyfsmc + "','" + zdxx.gyqk + "','" + zdxx.bz2 + "')";
                AccessHelper.excuteSqlNoClose(dbPath, sql);
            }
            if (dt.Rows.Count == 1)
            {
                if (!dt.Rows[0]["权利人"].ToString().Trim().Equals(zdxx.qlr.Trim()))//数据库中的原权利人和身份证识别的权利人不同
                {
                    if (!dt.Rows[0]["权利人"].ToString().Trim().Equals("") && !zdxx.qlr.Equals(""))//原权利人和新权利人都不为空
                    {
                        if (zdxx.yyqlrgx.Equals(""))
                        {
                            zdxx.bz1 = "原权利人为" + dt.Rows[0][2].ToString() + ",变更为" + zdxx.qlr + ",与原权利人关系不明" + zdxx.bz1;
                            zdxx.bz2 += ",与原权利人关系不明";
                        }
                        else
                        {
                            zdxx.bz1 = "原权利人为" + dt.Rows[0][2].ToString() + ",变更为" + zdxx.qlr + ",与原权利人关系为:" + zdxx.yyqlrgx + zdxx.bz1;
                        }
                    }
                }

                sql = "UPDATE zdxx SET 新权利人='" + zdxx.qlr + "',身份证号='" + zdxx.sfzh + "',证件类型名称='" + zdxx.zjlxmc + "',性别='" + zdxx.xb + "',电话号码='" + zdxx.dhhm + "',通讯地址='" + zdxx.txdz + "',邮政编码='" + zdxx.yzbm + "',建房年代='" + zdxx.jfnd + "',与户主关系='" + zdxx.yhzgx + "',备注='" + zdxx.bz1 + "',权利人类型名称='" + zdxx.qlrlxmc + "',权利类型名称='" + zdxx.qllxmc + "',共有方式名称='" + zdxx.gyfsmc + "',共有情况='" + zdxx.gyqk + "',备注2='" + zdxx.bz2 + "' WHERE 宗地号='" + zdxx.zdh + "'";
                AccessHelper.excuteSqlNoClose(dbPath, sql);
            }
        }

        private void IdcardReg(string sfzFulPath)
        {
            string jpgName = Path.GetFileName(sfzFulPath);
            string jpgNamePath = Path.GetDirectoryName(sfzFulPath);
            string zddmFoldName = Path.GetFileNameWithoutExtension(jpgNamePath);
            string APP_ID2 = "17634561";
            string API_KEY = "sCQuGeTfI4GctwIRt7Yho8Aw";
            string SECRET_KEY = "RxH8Fxs1DV8ob0oT94A8leGjfRLLhPFk";
            if (globalapi_key != "" && globalapp_id != "" && globalsecret_key != "") 
            {
                APP_ID2 = globalapp_id;
                API_KEY = globalapi_key;
                SECRET_KEY = globalsecret_key;
            }
            
            Ocr client = new Ocr(API_KEY, SECRET_KEY);
            client.Timeout = 60000;
            byte[] image = File.ReadAllBytes(sfzFulPath);
            string idCardSide = "front";
            JObject result = client.Idcard(image, idCardSide);
            JObject student = JsonConvert.DeserializeObject<JObject>(result.ToString());
            
                if (student.Count == 2)
                {
                    if (student["error_code"].ToString().Equals("17"))
                    {
                        MessageBox.Show("该AI Key已达到每日500次的免费试用次数上限，请更换AI Key后再识别\r\n当前识别进度以保存");
                    }
                    else
                    {
                        MessageBox.Show("AI Key错误 " + student.ToString());
                       
                    }
                    killThread = true;
                }
                else
                {
                    try
                    {
                        JToken[] jtoArray11 = student["words_result"]["住址"].ToArray();
                        JToken[] jtoArray9 = student["words_result"]["姓名"].ToArray();
                        JToken[] jtoArray7 = student["words_result"]["性别"].ToArray();
                        JToken[] jtoArray8 = student["words_result"]["公民身份号码"].ToArray();
                        string ss8 = jtoArray8[1].Last.ToString();
                        string sfzNumValid = "0";
                        if (ss8.Length == 18)
                        {
                            char[] chars = ss8.ToCharArray();
                            int int33 = int.Parse(ss8.Substring(0, 1));
                            int int32 = int.Parse(ss8.Substring(1, 1));
                            int int31 = int.Parse(ss8.Substring(2, 1));
                            int int30 = int.Parse(ss8.Substring(3, 1));
                            int int29 = int.Parse(ss8.Substring(4, 1));
                            int int28 = int.Parse(ss8.Substring(5, 1));
                            int int27 = int.Parse(ss8.Substring(6, 1));
                            int int26 = int.Parse(ss8.Substring(7, 1));
                            int int25 = int.Parse(ss8.Substring(8, 1));
                            int int24 = int.Parse(ss8.Substring(9, 1));
                            int int23 = int.Parse(ss8.Substring(10, 1));
                            int int22 = int.Parse(ss8.Substring(11, 1));
                            int int21 = int.Parse(ss8.Substring(12, 1));
                            int int20 = int.Parse(ss8.Substring(13, 1));
                            int int19 = int.Parse(ss8.Substring(14, 1));
                            int int18 = int.Parse(ss8.Substring(15, 1));
                            int int17 = int.Parse(ss8.Substring(16, 1));
                            int intCal = int33 * 7 + int32 * 9 + int31 * 10 + int30 * 5 + int29 * 8 + int28 * 4 + int27 * 2 + int26 + int25 * 6 + int24 * 3 + int23 * 7 + int22 * 9 + int21 * 10 + int20 * 5 + int19 * 8 + int18 * 4 + int17 * 2;
                            string outputStr = (intCal % 11).ToString();
                            string lastChar = ss8.Substring(17, 1);
                            switch (outputStr)
                            {
                                case "0":
                                    if (lastChar == "1")
                                    {
                                        sfzNumValid = "1";
                                    }
                                    break;
                                case "1":
                                    if (lastChar == "0")
                                    {
                                        sfzNumValid = "1";
                                    }
                                    break;
                                case "2":
                                    if (lastChar == "X")
                                    {
                                        sfzNumValid = "1";
                                    }
                                    break;
                                case "3":
                                    if (lastChar == "9")
                                    {
                                        sfzNumValid = "1";
                                    }
                                    break;
                                case "4":
                                    if (lastChar == "8")
                                    {
                                        sfzNumValid = "1";
                                    }
                                    break;
                                case "5":
                                    if (lastChar == "7")
                                    {
                                        sfzNumValid = "1";
                                    }
                                    break;
                                case "6":
                                    if (lastChar == "6")
                                    {
                                        sfzNumValid = "1";
                                    }
                                    break;
                                case "7":
                                    if (lastChar == "5")
                                    {
                                        sfzNumValid = "1";
                                    }
                                    break;
                                case "8":
                                    if (lastChar == "4")
                                    {
                                        sfzNumValid = "1";
                                    }
                                    break;
                                case "9":
                                    if (lastChar == "3")
                                    {
                                        sfzNumValid = "1";
                                    }
                                    break;
                                case "10":
                                    if (lastChar == "2")
                                    {
                                        sfzNumValid = "1";
                                    }
                                    break;
                            }
                        }
                        if (sfzNumValid == "1")
                        {
                            if (zdxx.sfzh.Length == 18 && !zdxx.sfzh.Equals(ss8))
                            {
                                zdxx.gyfsmc = "共有";
                                zdxx.sfzh += "/" + ss8;
                                zdxx.zjlxmc = "身份证";
                                zdxx.txdz += "/" + jtoArray11[1].Last.ToString();
                                zdxx.qlr += "/" + jtoArray9[1].Last.ToString();
                                zdxx.xb += "/" + jtoArray7[1].Last.ToString();
                            }
                            else
                            {
                                zdxx.gyfsmc = "单独所有";
                                zdxx.sfzh = ss8;
                                zdxx.zjlxmc = "身份证";
                                zdxx.txdz = jtoArray11[1].Last.ToString();
                                zdxx.qlr = jtoArray9[1].Last.ToString();
                                zdxx.xb = jtoArray7[1].Last.ToString();
                            }
                        }
                        else
                        {
                            zdxx.sfzh = "";
                            zdxx.zjlxmc = "";
                            zdxx.txdz = jtoArray11[1].Last.ToString();
                            zdxx.qlr = jtoArray9[1].Last.ToString();
                            zdxx.xb = jtoArray7[1].Last.ToString();
                            zdxx.bz2 += ",未能正确识别证件";
                        }
                    }
                    catch (Exception ex)
                    {
                        zdxx.bz2 += ",未能正确识别证件";
                        logTxtBool = false;
                        TxtHelper txt = new TxtHelper();
                        txt.txtWrite(logTxtFulPath, "AI识别报错：" + ex.Message + "\r\n文件位置：" + sfzFulPath + "\r\n");
                    }
                }
            
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            
                killThread = true;
               // AccessHelper.closeConnection();
                progressBar1.Visible = false;
                openDbfileButton.Enabled = true;
                openImgDirButton.Enabled = true;
                OKButton.Enabled = true;
           
        }

        private void Frm_InfoReg_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void Frm_InfoReg_FormClosing(object sender, FormClosingEventArgs e)
        {
            killThread = true;
        }
    }
}
